package com.achievo.know.application.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.achievo.know.application.FileApplication;
import com.achievo.know.domain.File;
import com.achievo.know.domain.FileAttachment;
import com.achievo.know.domain.FileAttachmentRepository;
import com.achievo.know.domain.FileRepository;
import com.achievo.know.domain.TempAttachment;
import com.achievo.know.domain.User;
import com.achievo.know.domain.UserFavorite;
import com.achievo.know.domain.UserRepository;
import com.achievo.know.pojo.Constants;
import com.achievo.know.pojo.FileStatus;
import com.dayatang.querychannel.service.QueryChannelService;
import com.dayatang.querychannel.support.Page;

@Service(value="fileApplication")
public class FileApplicationImpl implements FileApplication {
	
	@Autowired
	private QueryChannelService queryChannel;
	
	@Autowired
	private FileRepository fileRespository;
	
	@Autowired
	private FileAttachmentRepository fileAttachmentRepository;
	
	@Autowired
	private UserRepository userRepository;

	@Override
	public Page<File> queryPageByStatus(String userName,String status,int currentPage,int pageSize) {
		//默认按发布日期排序
		String orderby=" order by f.publishTime desc";
		//如果是提交中，则按提交日期排序
		if(status.equals(FileStatus.SUBMITTING)){
			orderby=" order by f.uploadTime desc";
		}
		String hql="from File f where f.status=? and f.uploadUser=?  "+orderby;
		//参数
		Object[] params=new Object[]{status,userName};
		return queryChannel.queryPagedResultByPageNo(hql, params, currentPage, pageSize);
	}
	
	@Override
	public Page<File> queryPageByStatus(String status, int currentPage,
			int pageSize,List<Long> cateIds, boolean isSuper) {
		StringBuilder hql=new StringBuilder();
		hql.append("from File f where f.status=?");
		if(!isSuper){
			if(cateIds!=null && cateIds.size()>0){
				StringBuilder cb=new StringBuilder();
				for(Long cateId:cateIds){
					cb.append(cateId).append(",");
				}
				cb.append(Constants.UPLOAD_DEFAULT_ID).append(",");
				if(cb.length()>0){
					cb.deleteCharAt(cb.length()-1);
					hql.append(" and f.categoryId in (").append(cb.toString()).append(")");
				}
			}else{
				StringBuilder cb=new StringBuilder();
				cb.append(Constants.UPLOAD_DEFAULT_ID).append(",");
				cb.deleteCharAt(cb.length()-1);
				hql.append(" and f.categoryId in (").append(cb.toString()).append(")");
			}
		}
		if(status.equals(FileStatus.SUBMITTING)){
			hql.append(" order by f.uploadTime desc");
		}else{
			hql.append(" order by f.publishTime desc");
		}
		//参数
		Object[] params=new Object[]{status};
		Page<File> page= queryChannel.queryPagedResultByPageNo(hql.toString(), params, currentPage, pageSize);
		if(status.equals(FileStatus.SUBMITTING)){
			List<File> list=new ArrayList<File>();
			for(File f:page.getResult()){
				List<FileAttachment> attachments=fileAttachmentRepository.listAttachment(f.getId(),1);
				f.setAttachments(attachments);
				list.add(f);
			}
			page.setResult(list);
		}
		return page;
	}



	public QueryChannelService getQueryChannel() {
		return queryChannel;
	}

	public void setQueryChannel(QueryChannelService queryChannel) {
		this.queryChannel = queryChannel;
	}
	
	

	public UserRepository getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	public FileRepository getFileRespository() {
		return fileRespository;
	}

	public void setFileRespository(FileRepository fileRespository) {
		this.fileRespository = fileRespository;
	}
	
	

	public FileAttachmentRepository getFileAttachmentRepository() {
		return fileAttachmentRepository;
	}

	public void setFileAttachmentRepository(
			FileAttachmentRepository fileAttachmentRepository) {
		this.fileAttachmentRepository = fileAttachmentRepository;
	}

	@Override
	public Page<File> queryMyFavorite(String userName, int currentPage,
			int pageSize) {
		String hql="select new File(f.id,f.fileName,f.category,uf.addTime) from File f ,User u,UserFavorite uf where f.id=uf.fileId and u.id=uf.userId and u.username=? order by f.publishTime desc ";
		Object[] params=new Object[]{userName};
		return queryChannel.queryPagedResultByPageNo(hql, params, currentPage, pageSize);
	}

	@Transactional
	@Override
	public void batchDelete(String[] ids) {
		fileRespository.batchDelete(ids);
	}

	@Override
	@Transactional
	public void batchDeleteFavorite(String[] ids) {
		fileRespository.batchDeleteFavorite(ids);
	}

	@Override
	@Transactional
	public void addFile(File file) {
		file.add();
		Iterator<FileAttachment> atts= file.getAttachments().iterator();
		while(atts.hasNext()){
			FileAttachment a=atts.next();
			a.setFkId(file.getId());
			a.setFkType(1);//FILE
			a.add();
		}
	}
	
	

	@Override
	@Transactional
	public void addFiles(List<File> files) {
		for(File f:files){
			f.setUploadTime(new Date());
			f.setPublishTime(new Date());
			addFile(f);
		}
	}
	
	@Override
	@Transactional
	public void saveOrUpdateFileAttachment(FileAttachment atts) {
		fileAttachmentRepository.save(atts);
	}

	@Override
	public FileAttachment getAttachmentByGuid(String guid) {
		return fileAttachmentRepository.getByGuid(guid);
	}

	@Override
	public FileAttachment getFileByName(String fileName) {
		FileAttachment f= fileAttachmentRepository.existsFileName(fileName);
		return f;
	}

	@Override
	@Transactional
	public void addTempAttachment(TempAttachment temp) {
		fileRespository.addTempAttachment(temp);
		
	}

	@Override
	public List<TempAttachment> loadTempAttach(String tempFileId) {
		String queryStr=" from TempAttachment a where a.tempFileId=?";
		Object[] params=new Object[]{tempFileId};
		return queryChannel.queryResult(queryStr, params);
	}

	@Override
	@Transactional
	public void deleteAttach(Long attachId) {
		fileRespository.delTempAttachment(attachId);
	}

	@Override
	public File getFile(Long fileId) {
		return fileRespository.get(fileId);
	}
	
	@Override
	@Transactional
	public File showFile(Long fileId) {
		File f=getFile(fileId);
		List<FileAttachment> attachments=fileAttachmentRepository.listAttachment(f.getId(),1);
		f.setAttachments(attachments);
		f.addBrowserSum();
		return f;
	}

	@Override
	public FileAttachment getAttachment(Long id) {
		return fileRespository.getAttachment(id);
	}
	
	
	@Override
	public List<FileAttachment> listAttachment(Long fkId,int type) {
		return fileAttachmentRepository.listAttachment(fkId,type);
	}

	@Override
	@Transactional
	public FileAttachment downAttachment(Long id) {
		FileAttachment a=getAttachment(id);
		fileRespository.addDownSum(a.getFkId());
		return a;
	}

	@Override
	@Transactional
	public void saveOrUpdateFile(File file) {
		fileRespository.save(file);
	}

	@Override
	@Transactional
	public void addFavorite(UserFavorite uf, String userId) {
		User user=userRepository.get(userId);
		uf.setUserId(user.getId());
		uf.add();
	}

	@Override
	@Transactional
	public void saveOrUpdateTempAttach(TempAttachment temp) {
		temp.save();
	}

	@Override
	@Transactional
	public void changeCate(String[] idArr,String category) {
		for(String id:idArr){
			if(StringUtils.isNotEmpty(id)){
				File file=getFile(NumberUtils.createLong(id));
				file.setCategory(category);
				fileRespository.save(file);
			}
		}
		
	}

	@Override
	@Transactional
	public void changeStatus(String[] idArr, String status) {
		for(String id:idArr){
			if(StringUtils.isNotEmpty(id)){
				File file=getFile(NumberUtils.createLong(id));
				file.setStatus(status);
				fileRespository.save(file);
			}
		}
		
	}
	
	
	
	
}
